<script setup>
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { message } from 'ant-design-vue';

const router = useRouter();

const userInfos = reactive({
    nickname: '',
    email: '',
    password: '',
    confirm: '',
});

const emailRules = [
    { required: true, message: '请输入电子邮箱' }
];
const pwdRules = [
    { required: true, message: '请输入登录密码' }
];
const confirmRules = [
    { required: true, message: '请确认登录密码' }
];

const onFinish = (values) => {
  console.log('Success:', values);
  const url = '/back/user/sign/up';
  const data = {
    email: values.email,
    password: values.password,
    nickname: values.nickname
  }
  // 通过 axios 发送 PUT 请求
  axios.put(url, data).then( resp => {
    // 解构赋值 并 将 message 重命名为 msg (等同于 const success = resp.data.success; const msg = resp.data.message; )
    const { success, message: msg } = resp.data;
    if (success) {
      router.push('/login');
    } else {
        message.error(msg)
    }
  }).catch( err => {
    console.log(err);
  });
};

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};
</script>

<template>
    <div class="register">
        <h1>用户注册</h1>
        <a-form :model="userInfos"
                :label-col="{ span: 4 }" 
                :wrapper-col="{ span: 16 }"
                autocomplete="off"
                @finish="onFinish"
                @finishFailed="onFinishFailed">
            <a-form-item label="昵称" name="nickname">
                <a-input v-model:value="userInfos.nickname"/>
            </a-form-item>
            <a-form-item label="邮箱" name="email" :rules="emailRules">
                <a-input v-model:value="userInfos.email"/>
            </a-form-item>
            <a-form-item label="登录密码" name="password" :rules="pwdRules">
                <a-input-password v-model:value="userInfos.password"/>
            </a-form-item>
            <a-form-item label="确认密码" name="confirm" :rules="confirmRules">
                <a-input-password v-model:value="userInfos.confirm"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
                <a-button type="primary" html-type="submit">注册</a-button>
            </a-form-item>
        </a-form>
        <p>
            <router-link to="/login" class="link">登录</router-link>
        </p>
    </div>
</template>

<style scoped>
.register {
    margin-top: 20vh;
    margin-left: 25vw;
    width: 50vw;
}
h1,p{
    text-align: center;
}
</style>